﻿using System.Linq;
using NHibernate;
using NHibernate.Linq;
using NotMyself.Oxite.Data.LinqToNHibernateProvider.Specification;

namespace NotMyself.Oxite.Data.LinqToNHibernateProvider
{
    public class Repository<T>
        : IRepository<T>, IPagedRepository<T>
    {
        public Repository(ISessionFactory sessionFactory)
        {
            this.sessionFactory = sessionFactory;
        }


        private ISessionFactory sessionFactory { get; set; }

        #region IPagedRepository<T> Members

        public IQueryable<T> GetPagedList(SpecificationBase<T> query,
                                          int pageSize, int pageId)
        {
            if (pageId == 0) pageId = 1;
            return GetList(query).Take(pageSize).Skip(pageId*pageSize);
        }

        #endregion

        #region IRepository<T> Members

        public IQueryable<T> GetList()
        {
            return (from entity in sessionFactory.OpenSession().Linq<T>() select entity);
        }


        public T GetById(long id)
        {
            return sessionFactory.OpenSession().Get<T>(id);
        }


        public void Save(T entity)
        {
            sessionFactory.OpenSession().SaveOrUpdate(entity);
        }

        public void Delete(T entity)
        {
            sessionFactory.OpenSession().Delete(entity);
            sessionFactory.OpenSession().Flush();
        }


        /// <returns></returns>
        public T GetOne(SpecificationBase<T> query)
        {
            return query.SatisfyingElementFrom(sessionFactory.OpenSession().Linq<T>());
        }


        /// <returns></returns>
        public IQueryable<T> GetList(SpecificationBase<T> query)
        {
            return query.SatisfyingElementsFrom(sessionFactory.OpenSession().Linq<T>());
        }

        #endregion
    }
}